package com.leetcode.p200;

import com.bean.TreeNode;
import com.utils.TreeUtils;

import java.util.Deque;
import java.util.LinkedList;

public class Test230 {

    public int kthSmallest(TreeNode root, int k) {
        Deque<TreeNode> stack = new LinkedList<>();

        int index = 0;
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }

            TreeNode node = stack.poll();
            index++;

            if (index == k) {
                return node.val;
            }
            root = node.right;

        }
        return 0;
    }

    public static void main(String[] args) {
        TreeNode treeNode = TreeUtils.buildTree("5,3,6,2,4,null,null,1");
        TreeUtils.showTree(treeNode);

        Test230 test = new Test230();
        int result = test.kthSmallest(treeNode, 3);
        System.out.println(result);
    }

}
